document.addEventListener('DOMContentLoaded', function() {
    // Socket.IO连接
    const socket = io();
    
    // DOM元素
    const startButton = document.getElementById('start-analysis');
    const resetButton = document.getElementById('reset-all');
    const progressBar = document.getElementById('analysis-progress');
    const aiChatBtn = document.getElementById('ai-chat-btn');
    
    // 图表实例
    let diagnosisChart = null;
    
    // 加载疾病配置信息
    let diseaseConfig = null;
    let diseaseConfigLoadRetries = 0;

    function loadDiseaseConfig() {
    fetch('/static/config/diseases.json')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`状态码: ${response.status}`);
                }
                return response.json();
            })
        .then(data => {
            diseaseConfig = data;
        })
            .catch(error => {
                diseaseConfigLoadRetries++;
                if (diseaseConfigLoadRetries < 3) {
                    setTimeout(loadDiseaseConfig, 1000);
                } else {
                    showAlert('警告', '疾病信息加载失败，将使用备用数据');
                    // 提供基本的备用数据以防配置文件加载失败
                    diseaseConfig = {
                        "正常": {
                            "name": "正常",
                            "description": "眼底检查未发现明显疾病特征。",
                            "risk_factors": [],
                            "suggestions": ["继续保持良好的用眼习惯", "定期进行眼部检查"]
                        },
                        "近视": {
                            "name": "近视",
                            "description": "近视是一种常见的屈光不正，远处物体在视网膜前成像，导致看远处物体模糊。",
                            "risk_factors": ["遗传因素", "长时间近距离用眼", "缺乏户外活动"],
                            "suggestions": ["定期检查视力", "户外活动", "适当休息眼睛", "避免长时间用眼"]
                        }
                    };
                }
            });
    }

    loadDiseaseConfig();
    
    // 开始分析按钮点击事件
    startButton.addEventListener('click', async function() {
        
        // 禁用按钮
        startButton.disabled = true;
        resetButton.disabled = true;
        
        // 获取当前模式
        const activeTab = document.querySelector('.tab-pane.active');
        const isBatchMode = activeTab.id === 'single-eye' 
            ? document.getElementById('batch-mode-single').checked
            : document.getElementById('batch-mode-both').checked;
        
        // 额外的逻辑检查
        if (!isBatchMode && activeTab.id === 'both-eyes') {
            // 检查左右眼是否为同一张图片
            const leftImg = document.getElementById('left-image-input').files[0];
            const rightImg = document.getElementById('right-image-input').files[0];
            
            if (leftImg && rightImg && leftImg.name === rightImg.name && leftImg.size === rightImg.size) {
                showAlert('错误', '左右眼不能使用相同的图片');
                resetProgress();
                return;
            }
        }
        
        try {
            if (isBatchMode) {
                await handleBatchAnalysis(activeTab.id);
            } else {
                await handleSingleAnalysis(activeTab.id);
            }
        } catch (error) {
            showAlert('错误', error.message || '分析过程中发生错误');
            resetProgress();
        }
    });
    
    // 重置按钮点击事件
    resetButton.addEventListener('click', function() {
        resetAll();
    });
    
    // AI问答按钮点击事件
    aiChatBtn.addEventListener('click', function() {
        // openAIChatModal();
    });
    
    // 连接状态测试
    socket.on('connect', function() {
        console.log('WebSocket连接成功');
    });

    socket.on('disconnect', function() {
        console.log('WebSocket连接断开');
    });

    socket.on('connect_error', function(error) {
        console.error('WebSocket连接错误:', error);
    });
    
    // 增强分析更新处理
    socket.on('analysis_update', function(data) {
        console.log('收到分析更新:', data);
        
        if (data.status === 'completed') {
            console.log('分析完成，处理结果...');
            handleAnalysisComplete(data);
        } else if (data.status === 'error') {
            showError(data.message || '分析过程中发生错误');
        }
        
        // 更新进度条，包含处理文件数信息
        if (data.progress !== undefined) {
            console.log(`更新进度: ${data.progress}%, 已处理: ${data.processed_files || 0}/${data.total_files || 0}`);
            updateProgress(data.progress, data.processed_files, data.total_files);
        }
    });
    
    // 修改批量分析进度处理
    socket.on('analysis_progress', function(data) {
        if (data.progress !== undefined) {
            updateProgress(data.progress, data.processed_files, data.total_files);
        }
        if (data.message) {
            console.log('批量分析进度:', data.message);
        }
    });
    
    // 添加文件处理状态监听
    socket.on('file_processed', function(data) {
        // 更新实时处理状态
        updateProcessingStatus(data);
    });
    
    // 处理单张图片分析
    async function handleSingleAnalysis(mode) {
        // 显示进度条动画
        updateProgress(0);
        
        try {
            // 先上传图片
            if (mode === 'single-eye') {
                // 上传单眼图像
                const singleEyeFile = document.getElementById('single-image-input').files[0];
                if (singleEyeFile) {
                    const singleFormData = new FormData();
                    singleFormData.append('file', singleEyeFile);
                    
                    const singleResponse = await fetch('/upload', {
                        method: 'POST',
                        body: singleFormData
                    });
                    
                    if (!singleResponse.ok) {
                        throw new Error('图像上传失败');
                    }
                    
                    // 确保上传成功
                    const singleResult = await singleResponse.json();
                    if (!singleResult.success) {
                        throw new Error(singleResult.error || '图像上传失败');
                    }
                } else {
                    throw new Error('请选择图像');
                }
            } else if (mode === 'both-eyes') {
                // 上传左眼图像
                const leftEyeFile = document.getElementById('left-image-input').files[0];
                if (leftEyeFile) {
                    const leftFormData = new FormData();
                    leftFormData.append('file', leftEyeFile);
                    leftFormData.append('eye', 'left');
                    
                    const leftResponse = await fetch('/upload', {
                        method: 'POST',
                        body: leftFormData
                    });
                    
                    if (!leftResponse.ok) {
                        throw new Error('左眼图像上传失败');
                    }
                    
                    // 确保上传成功
                    const leftResult = await leftResponse.json();
                    if (!leftResult.success) {
                        throw new Error(leftResult.error || '左眼图像上传失败');
                    }
                } else {
                    throw new Error('请选择左眼图像');
                }
                
                // 上传右眼图像
                const rightEyeFile = document.getElementById('right-image-input').files[0];
                if (rightEyeFile) {
                    const rightFormData = new FormData();
                    rightFormData.append('file', rightEyeFile);
                    rightFormData.append('eye', 'right');
                    
                    const rightResponse = await fetch('/upload', {
                        method: 'POST',
                        body: rightFormData
                    });
                    
                    if (!rightResponse.ok) {
                        throw new Error('右眼图像上传失败');
                    }
                    
                    // 确保上传成功
                    const rightResult = await rightResponse.json();
                    if (!rightResult.success) {
                        throw new Error(rightResult.error || '右眼图像上传失败');
                    }
                } else {
                    throw new Error('请选择右眼图像');
                }
            }
            
            // 图片上传成功后，发送分析请求
            const formData = new FormData();
            
            // 添加患者信息
            formData.append('patient_id', document.getElementById('patient-id').value);
            formData.append('patient_name', document.getElementById('patient-name').value);
            formData.append('age', document.getElementById('patient-age').value);
            formData.append('gender', document.getElementById('patient-gender').value);
            formData.append('exam_date', new Date().toISOString().split('T')[0]);
            
            // 添加模式信息
            formData.append('mode', mode === 'both-eyes' ? 'both' : 'single');
            
            // 发送分析请求
            const response = await fetch('/analyze', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                throw new Error('分析请求失败');
            }
            
            const result = await response.json();
            if (!result.success) {
                throw new Error(result.message || '分析过程中发生错误');
            }
            
            // 分析已开始，后续进度将通过WebSocket更新
            updateProgress(10);
        } catch (error) {
            console.error('分析请求错误:', error);
            showAlert('错误', error.message || '无法启动分析过程');
            resetProgress();
        }
    }
    
    // 处理批量分析
    async function handleBatchAnalysis(mode) {
        try {
            // 显示进度条动画
            updateProgress(0);
            
            // 检查文件夹
            if (mode === 'both-eyes') {
                const leftFiles = Array.from(document.getElementById('left-folder-input').files)
                    .filter(f => f.type.match('image/(jpeg|png|jpg)'));
                const rightFiles = Array.from(document.getElementById('right-folder-input').files)
                    .filter(f => f.type.match('image/(jpeg|png|jpg)'));
                
                if (leftFiles.length !== rightFiles.length) {
                    throw new Error('左右眼图片数量不匹配');
                }
                
                const leftNames = leftFiles.map(f => f.name);
                const rightNames = rightFiles.map(f => f.name);
                
                // 检查文件名是否匹配
                const mismatchedFiles = leftNames.filter(name => !rightNames.includes(name));
                if (mismatchedFiles.length > 0) {
                    throw new Error('左右眼图片文件名不匹配');
                }
            }
            
            // 构建批量分析请求
            const formData = new FormData();
            
            // 添加患者信息 - 检查是否使用批量病人信息
            const isBatchPatientInfo = document.getElementById('batch-patient-info').checked;

            if (!isBatchPatientInfo) {
                // 使用单个患者信息
                formData.append('patient_id', document.getElementById('patient-id').value || '');
                formData.append('patient_name', document.getElementById('patient-name').value || '');
                formData.append('age', document.getElementById('patient-age').value || '');
                formData.append('gender', document.getElementById('patient-gender').value || '');
            } else {
                // 使用批量患者信息
                formData.append('batch_patient_info', 'true');
            }
            console.log(formData);
            
            // 使用当前日期作为检查日期
            formData.append('exam_date', new Date().toISOString().split('T')[0]);
            
            // 添加模式信息
            formData.append('mode', mode === 'both-eyes' ? 'both' : 'single');
            formData.append('batch', 'true');
            
            // 对于批量模式，上传文件列表
            if (mode === 'single-eye') {
                const files = Array.from(document.getElementById('single-folder-input').files);
                // 只上传有效图片文件
                const imageFiles = files.filter(f => f.type.match('image/(jpeg|png|jpg)'));
                console.log(`正在处理 ${imageFiles.length} 张单眼图片`);
                
                // 检查批量大小，避免一次上传过多文件
                if (imageFiles.length > 100) {
                    showAlert('警告', '单次处理图片数量过多，请减少选择的图片数量（建议少于100张）');
                    resetProgress();
                    return;
                }
                
                // 批量信息模式下，处理每个文件
                for (let i = 0; i < imageFiles.length; i++) {
                    const file = imageFiles[i];
                    formData.append('files[]', file);
                    // 如果启用了批量患者信息，尝试获取并添加患者信息
                    if (isBatchPatientInfo && window.patientInfoModule) {
                        const fileName = file.name;
                        const patient = window.patientInfoModule.getPatientByPhotoName(fileName);
                        if (patient) {
                            // 为每个文件添加对应的患者信息
                            console.log(`匹配到文件 ${fileName} 的患者信息:`, patient);
                            formData.append(`file_${i}_patient_id`, patient.id);
                            formData.append(`file_${i}_patient_name`, patient.name);
                            formData.append(`file_${i}_patient_gender`, patient.gender);
                            formData.append(`file_${i}_patient_age`, patient.age);
                        } else {
                            console.log(`未找到文件 ${fileName} 的患者信息`);
                        }
                    }
                }
            } else { // both-eyes 模式
                const leftFiles = Array.from(document.getElementById('left-folder-input').files)
                    .filter(f => f.type.match('image/(jpeg|png|jpg)'));
                const rightFiles = Array.from(document.getElementById('right-folder-input').files)
                    .filter(f => f.type.match('image/(jpeg|png|jpg)'));
                
                console.log(`正在处理 ${leftFiles.length} 对眼睛图片`);
                
                // 检查批量大小
                if (leftFiles.length > 50) {
                    showAlert('警告', '单次处理图片对数过多，请减少选择的图片数量（建议少于50对）');
                    resetProgress();
                    return;
                }
                
                // 匹配的文件应具有相同的索引
                const sortedLeftFiles = leftFiles.sort((a, b) => a.name.localeCompare(b.name));
                const sortedRightFiles = rightFiles.sort((a, b) => a.name.localeCompare(b.name));
                
                for (let i = 0; i < sortedLeftFiles.length; i++) {
                    const leftFile = sortedLeftFiles[i];
                    const rightFile = sortedRightFiles[i];
                    
                    formData.append('left_files[]', leftFile);
                    formData.append('right_files[]', rightFile);
                    
                    // 如果启用了批量患者信息，尝试获取并添加患者信息
                    if (isBatchPatientInfo && window.patientInfoModule) {
                        const fileName = leftFile.name; // 使用左眼文件名进行匹配
                        const patient = window.patientInfoModule.getPatientByPhotoName(fileName);
                        
                        if (patient) {
                            // 为每对文件添加对应的患者信息
                            console.log(`匹配到文件 ${fileName} 的患者信息:`, patient);
                            formData.append(`file_${i}_patient_id`, patient.id);
                            formData.append(`file_${i}_patient_name`, patient.name);
                            formData.append(`file_${i}_patient_gender`, patient.gender);
                            formData.append(`file_${i}_patient_age`, patient.age);
                        } else {
                            console.log(`未找到文件 ${fileName} 的患者信息`);
                        }
                    }
                }
            }
            
            // 发送批量分析请求
            const response = await fetch('/analyze_batch', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                throw new Error('批量分析请求失败');
            }
            
            const result = await response.json();
            if (!result.success) {
                throw new Error(result.message || '批量分析过程中发生错误');
            }
            
            // 批量分析已开始，后续进度将通过WebSocket更新
            updateProgress(10);
            showAlert('成功', '批量分析已开始，请等待处理完成');
        } catch (error) {
            console.error('批量分析请求错误:', error);
            showAlert('错误', error.message || '无法启动批量分析过程');
            resetProgress();
        }
    }
    
    // 处理分析完成
    function handleAnalysisComplete(data) {
        if (data.saved_files && data.saved_files.length > 0) {
            // 显示完成通知
            showAlert('处理完成', `成功处理 ${data.success_count} 个文件，失败 ${data.failed_count} 个文件`, 'success');
            
            // 创建结果摘要模态框
            const modalHTML = `
                <div class="modal fade" id="batchResultModal" tabindex="-1">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">
                                    <i class="bi bi-check-circle-fill text-success me-2"></i>
                                    批量分析完成
                                </h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <div class="alert alert-success">
                                    <h6 class="mb-2">处理结果统计</h6>
                                    <p class="mb-1">总计处理: ${data.total_files} 个文件</p>
                                    <p class="mb-1">成功: ${data.success_count} 个</p>
                                    <p class="mb-1">失败: ${data.failed_count} 个</p>
                                    <p class="mb-0">输出目录: <code>${data.output_dir}</code></p>
                                </div>
                                
                                <div class="results-table mt-4">
                                    <h6>处理结果详情</h6>
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>诊断结果</th>
                                                    <th>置信度</th>
                                                    <th>操作</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                ${data.results.map((result, index) => {
                                                    if (!result.success) {
                                                        return `
                                                            <tr class="table-danger">
                                                                <td>${index + 1}</td>
                                                                <td colspan="3">处理失败: ${result.message || '未知错误'}</td>
                                                            </tr>
                                                        `;
                                                    }
                                                    
                                                    const diagnosis = result.diagnosis.predicted_class;
                                                    const confidence = (result.diagnosis.confidence * 100).toFixed(2);
                                                    
                                                    return `
                                                        <tr>
                                                            <td>${index + 1}</td>
                                                            <td>${diagnosis}</td>
                                                            <td>${confidence}%</td>
                                                            <td>
                                                                <button class="btn btn-sm btn-outline-primary view-result"
                                                                        data-path="${result.saved_image}">
                                                                    查看结果
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    `;
                                                }).join('')}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                                <a href="${data.summary_file}" class="btn btn-primary" download>
                                    <i class="bi bi-download me-1"></i>下载摘要
                                </a>
                                <button type="button" class="btn btn-success" onclick="openOutputDir('${data.output_dir}')">
                                    <i class="bi bi-folder me-1"></i>打开目录
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // 添加模态框到页面并显示
            if (document.getElementById('batchResultModal')) {
                document.getElementById('batchResultModal').remove();
            }
            document.body.insertAdjacentHTML('beforeend', modalHTML);
            
            const modal = new bootstrap.Modal(document.getElementById('batchResultModal'));
            modal.show();
            
            // 添加查看结果事件监听
            document.querySelectorAll('.view-result').forEach(btn => {
                btn.addEventListener('click', function() {
                    const imagePath = this.getAttribute('data-path');
                    window.open(imagePath, '_blank');
                });
            });
        } else {
            // 单张图像分析结果，显示在页面上
            const results = data.results;
            
            if (results && results.success) {
                console.log("渲染页面");
                // 显示诊断结果
                updateDiagnosisResult(results.diagnosis);
                
                // 显示疾病信息
                updateDiseaseInfo(results.diagnosis);
                
                // 更新患者信息
                if (results.patient_info) {
                    updatePatientInfo(results.patient_info);
                }
                
                // 保存结果图像
                saveResultImage(results);
            } else {
                // 分析失败，显示错误消息
                showAlert('错误', results ? results.message : '分析失败，未返回有效结果', 'danger');
                resetProgress();
            }
        }
    }
    
    // 更新进度条
    function updateProgress(percent, processedFiles, totalFiles) {
        progressBar.style.width = percent + '%';
        progressBar.setAttribute('aria-valuenow', percent);
        
        // 如果提供了处理文件数信息，显示详细进度
        if (processedFiles !== undefined && totalFiles !== undefined) {
            progressBar.textContent = `${percent}% (${processedFiles}/${totalFiles})`;
        } else {
            progressBar.textContent = percent + '%';
        }
    }
    
    // 重置进度
    function resetProgress() {
        updateProgress(0);
        startButton.disabled = false;
        resetButton.disabled = false;
    }
    
    // 重置所有
    function resetAll() {
        // 重置表单
        document.getElementById('patient-form').reset();
        
        // 重置上传
        resetUploads();
        
        // 重置进度条
        resetProgress();
        
        // 重置诊断结果
        resetDiagnosisResult();
        
        // 重置文件夹选择UI
        resetFolderSelectionUI();
        
        // 重置结果区域的显示
        toggleResultSections(false);
    }
    
    // 重置上传
    function resetUploads() {
        // 重置单眼模式
        document.getElementById('single-image-input').value = '';
        document.getElementById('single-folder-input').value = '';
        resetPreview(document.getElementById('single-image-preview'));
        
        // 重置双眼模式
        document.getElementById('left-image-input').value = '';
        document.getElementById('right-image-input').value = '';
        document.getElementById('left-folder-input').value = '';
        document.getElementById('right-folder-input').value = '';
        resetPreview(document.getElementById('left-eye-preview'));
        resetPreview(document.getElementById('right-eye-preview'));
        
        // 重置批量模式开关
        document.getElementById('batch-mode-single').checked = false;
        document.getElementById('batch-mode-both').checked = false;
        
        // 显示单张上传模式
        document.querySelector('#single-eye-upload .single-upload-mode').classList.remove('d-none');
        document.querySelector('#single-eye-upload .batch-upload-mode').classList.add('d-none');
        document.querySelector('#left-eye-upload .single-upload-mode').classList.remove('d-none');
        document.querySelector('#left-eye-upload .batch-upload-mode').classList.add('d-none');
        document.querySelector('#right-eye-upload .single-upload-mode').classList.remove('d-none');
        document.querySelector('#right-eye-upload .batch-upload-mode').classList.add('d-none');
    }
    
    // 重置预览
    function resetPreview(preview) {
        if (preview) {
            preview.src = '';
            preview.classList.add('d-none');
            const placeholder = preview.parentElement.querySelector('.upload-placeholder');
            if (placeholder) {
                placeholder.classList.remove('d-none');
            }
        }
    }
    
    // 重置诊断结果
    function resetDiagnosisResult() {
        // 重置图表
        if (diagnosisChart) {
            diagnosisChart.destroy();
            diagnosisChart = null;
        }
        
        // 重置置信度信息
        document.getElementById('confidence-info').innerHTML = '';
        
        // 重置疾病信息
        document.getElementById('disease-info-content').innerHTML = `
            <div class="text-center text-muted">
                <i class="bi bi-arrow-up-circle display-4"></i>
                <p class="mt-3">请先上传眼底图像进行分析</p>
            </div>
        `;
    }
    
    // 更新诊断结果
    function updateDiagnosisResult(diagnosis) {
        console.log('开始更新诊断结果:', diagnosis);
        
        try {
            // 更新置信度信息 - 使用现有的confidence-info元素
        const confidenceInfo = document.getElementById('confidence-info');
            if (confidenceInfo) {
                const confidencePercent = (diagnosis.confidence * 100).toFixed(2);
        confidenceInfo.innerHTML = `
            <div class="alert ${diagnosis.predicted_class === '正常' ? 'alert-success' : 'alert-warning'}">
                <h6 class="mb-2"><i class="bi bi-clipboard2-pulse me-2"></i>诊断结果</h6>
                <div class="d-flex justify-content-between align-items-center">
                    <span>预测类别：<strong>${diagnosis.predicted_class}</strong></span>
                    <span>置信度：<strong>${confidencePercent}%</strong></span>
                </div>
            </div>
        `;
                console.log('已更新置信度信息');
            } else {
                console.error('找不到置信度信息元素 #confidence-info');
                showAlert('错误', '找不到置信度信息元素，请刷新页面');
            }
        
            // 更新图表 - 使用现有的diagnosis-chart元素
        createDiagnosisChart(diagnosis.class_probabilities);
            console.log('已更新诊断图表');
            
        } catch (error) {
            console.error('更新诊断结果时出错:', error);
            showAlert('错误', '更新诊断结果时出错: ' + error.message);
        }
    }
    
    // 更新疾病信息
    function updateDiseaseInfo(diagnosis) {
        console.log('开始更新疾病信息:', diagnosis);
        
        try {
            // 使用第三象限的disease-info-content元素
        const container = document.getElementById('disease-info-content');
            if (!container) {
                console.error('找不到疾病信息容器 #disease-info-content');
                showAlert('错误', '找不到疾病信息容器，请刷新页面');
                return;
            }
            
            // 检查diseaseConfig是否加载
            if (!diseaseConfig) {
                console.error('疾病配置信息尚未加载');
                container.innerHTML = '<div class="text-center text-muted">疾病信息未加载，请稍后刷新重试</div>';
                return;
            }
            
        const diseaseInfo = diseaseConfig[diagnosis.predicted_class];
            console.log('获取到疾病信息:', diseaseInfo);
        
        if (!diseaseInfo) {
                console.warn('没有找到相关疾病信息:', diagnosis.predicted_class);
                container.innerHTML = `<div class="text-center text-muted">暂无关于"${diagnosis.predicted_class}"的详细信息</div>`;
            return;
        }
        
        container.innerHTML = `
            <div class="disease-info">
                    <h6><i class="bi bi-clipboard-pulse me-2"></i>${diseaseInfo.name || diagnosis.predicted_class}</h6>
                    <p>${diseaseInfo.description || '暂无描述'}</p>
                
                    ${diseaseInfo.risk_factors && diseaseInfo.risk_factors.length > 0 ? `
                    <h6 class="mt-4"><i class="bi bi-exclamation-triangle me-2"></i>风险因素</h6>
                    <ul class="risk-factors">
                        ${diseaseInfo.risk_factors.map(factor => `<li>${factor}</li>`).join('')}
                    </ul>
                ` : ''}
                
                <h6 class="mt-4"><i class="bi bi-lightbulb me-2"></i>建议</h6>
                <ul class="suggestions">
                        ${(diseaseInfo.suggestions || ['请咨询专业医生获取进一步建议']).map(suggestion => `<li>${suggestion}</li>`).join('')}
                </ul>
            </div>
        `;
            console.log('已更新疾病信息');
            
        } catch (error) {
            console.error('更新疾病信息时出错:', error);
            const container = document.getElementById('disease-info-content');
            if (container) {
                container.innerHTML = `<div class="text-center text-muted">加载疾病信息时出错: ${error.message}</div>`;
            }
        }
    }
    
    // 创建诊断图表
    function createDiagnosisChart(probabilities) {
        try {
            const ctx = document.getElementById('diagnosis-chart');
            if (!ctx) {
                console.error('找不到图表画布元素 #diagnosis-chart');
                return;
            }
            
            console.log('准备创建图表，数据:', probabilities);
        
        // 如果已存在图表，先销毁
        if (diagnosisChart) {
            diagnosisChart.destroy();
        }
        
        // 准备数据
        const labels = Object.keys(probabilities);
        const data = Object.values(probabilities).map(p => p * 100);
            
            console.log('图表数据准备完成:', {labels, data});
        
        // 创建图表
        diagnosisChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: '疾病概率 (%)',
                    data: data,
                    backgroundColor: labels.map(label => 
                        label === '正常' ? 'rgba(40, 167, 69, 0.7)' : 'rgba(52, 152, 219, 0.7)'),
                    borderColor: labels.map(label => 
                        label === '正常' ? 'rgba(40, 167, 69, 1)' : 'rgba(52, 152, 219, 1)'),
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '概率 (%)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '疾病类别'
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `概率: ${context.raw.toFixed(2)}%`;
                            }
                        }
                    }
                }
            }
        });
            
            console.log('图表创建成功');
        } catch (error) {
            console.error('创建图表时出错:', error);
            showAlert('错误', '创建诊断图表时出错，请刷新重试');
        }
    }
    
    // 显示警告提示
    function showAlert(title, message, type = 'warning') {
        // 创建警告提示元素
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show toast-alert`;
        alertDiv.innerHTML = `
            <strong>${title}：</strong> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        // 创建或获取警告容器
        let alertContainer = document.getElementById('alert-container');
        if (!alertContainer) {
            alertContainer = document.createElement('div');
            alertContainer.id = 'alert-container';
            alertContainer.className = 'position-fixed top-0 end-0 p-3';
            alertContainer.style.zIndex = '1050';
            document.body.appendChild(alertContainer);
        }
        
        // 添加警告到容器
        alertContainer.appendChild(alertDiv);
        
        // 3秒后自动消失
        setTimeout(() => {
            const alert = bootstrap.Alert.getOrCreateInstance(alertDiv);
            alert.close();
            
            // 移除元素后检查容器是否为空，如果为空则移除容器
            setTimeout(() => {
                if (alertContainer.children.length === 0) {
                    alertContainer.remove();
                }
            }, 300);
        }, 3000);
    }
    
    // 添加保存结果图片的函数
    function saveResultImage(results) {
        // 创建结果容器
        const resultContainer = document.createElement('div');
        resultContainer.className = 'result-capture-container';
        resultContainer.style.width = '1200px';
        resultContainer.style.padding = '30px';
        resultContainer.style.backgroundColor = 'white';
        resultContainer.style.position = 'fixed';
        resultContainer.style.left = '-9999px';
        resultContainer.style.top = '0';
        
        // 获取病人信息
        const patientInfo = results.patient_info;
        const diagnosisInfo = results.diagnosis;
        
        // 使用当前日期作为默认日期
        const currentDate = new Date();
        const dateStr = currentDate.toISOString().split('T')[0];
        const timeStr = currentDate.toISOString().replace(/[:.]/g, '-').replace('T', '_').split('Z')[0];
        
        // 确定文件名
        let fileName;
        if (!patientInfo.id && !patientInfo.name) {
            fileName = `诊断结果_${timeStr}.png`;
        } else {
            fileName = `${patientInfo.id || '未知ID'}-${patientInfo.name || '未知姓名'}-${patientInfo.age || '未知年龄'}-${dateStr}.png`;
        }
        
        // 获取分析的图片
        let imageHtml = '';
        if (results.mode === 'both') {
            // 双眼模式
            const leftImg = document.getElementById('left-eye-preview');
            const rightImg = document.getElementById('right-eye-preview');
            imageHtml = `
                <div style="display: flex; justify-content: space-around; margin-bottom: 30px;">
                    <div style="text-align: center;">
                        <h5 style="color: #2c3e50; margin-bottom: 10px;">左眼</h5>
                        <img src="${leftImg.src}" style="max-height: 300px; max-width: 400px; object-fit: contain;" />
                    </div>
                    <div style="text-align: center;">
                        <h5 style="color: #2c3e50; margin-bottom: 10px;">右眼</h5>
                        <img src="${rightImg.src}" style="max-height: 300px; max-width: 400px; object-fit: contain;" />
                    </div>
                </div>
            `;
        } else {
            // 单眼模式
            const singleImg = document.getElementById('single-image-preview');
            imageHtml = `
                <div style="text-align: center; margin-bottom: 30px;">
                    <h5 style="color: #2c3e50; margin-bottom: 10px;">分析图像</h5>
                    <img src="${singleImg.src}" style="max-height: 300px; max-width: 600px; object-fit: contain;" />
                </div>
            `;
        }
        
        // 构建结果HTML，添加图片部分
        resultContainer.innerHTML = `
            <div style="text-align: center; margin-bottom: 20px;">
                <h2 style="color: #3498db; margin-bottom: 10px;">眼科疾病智能诊断报告</h2>
                <p style="color: #666; font-size: 14px;">生成时间: ${currentDate.toLocaleString()}</p>
            </div>
            
            ${imageHtml}
            
            <div style="display: flex; margin-bottom: 30px;">
                <div style="flex: 1; padding-right: 20px;">
                    <h4 style="color: #2c3e50; border-bottom: 2px solid #eee; padding-bottom: 10px;">病人信息</h4>
                    <table style="width: 100%; border-collapse: collapse;">
                        <tr>
                            <td style="padding: 8px 0; font-weight: bold; width: 100px;">病历号:</td>
                            <td style="padding: 8px 0;">${patientInfo.id || '未填写'}</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; font-weight: bold;">姓名:</td>
                            <td style="padding: 8px 0;">${patientInfo.name || '未填写'}</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; font-weight: bold;">性别:</td>
                            <td style="padding: 8px 0;">${patientInfo.gender || '未填写'}</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; font-weight: bold;">年龄:</td>
                            <td style="padding: 8px 0;">${patientInfo.age ? patientInfo.age + '岁' : '未填写'}</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; font-weight: bold;">检查日期:</td>
                            <td style="padding: 8px 0;">${dateStr}</td>
                        </tr>
                    </table>
                </div>
                
                <div style="flex: 1; padding-left: 20px; border-left: 1px solid #eee;">
                    <h4 style="color: #2c3e50; border-bottom: 2px solid #eee; padding-bottom: 10px;">诊断结果</h4>
                    <div style="margin: 15px 0;">
                        <p style="font-size: 18px; font-weight: bold; color: #3498db;">
                            ${diagnosisInfo.predicted_class}
                        </p>
                        <p style="color: #666;">
                            置信度: ${(diagnosisInfo.confidence * 100).toFixed(2)}%
                        </p>
                    </div>
                </div>
            </div>
            
            <div style="margin-bottom: 30px;">
                <h4 style="color: #2c3e50; border-bottom: 2px solid #eee; padding-bottom: 10px;">概率分布</h4>
                <div style="height: 300px; margin-top: 20px;">
                    <canvas id="report-chart" width="1140" height="300"></canvas>
                </div>
            </div>
            
            <div>
                <h4 style="color: #2c3e50; border-bottom: 2px solid #eee; padding-bottom: 10px;">疾病信息</h4>
                <div style="margin-top: 15px;">
                    ${generateDiseaseInfoHTML(diagnosisInfo.predicted_class)}
                </div>
            </div>
            
            <div style="margin-top: 30px; text-align: center; color: #999; font-size: 12px; border-top: 1px solid #eee; padding-top: 20px;">
                本报告由AI辅助生成，仅供参考，请以医生诊断为准。
            </div>
        `;
        
        // 添加到文档
        document.body.appendChild(resultContainer);
        
        // 创建图表
        const ctx = document.getElementById('report-chart').getContext('2d');
        const probabilities = diagnosisInfo.class_probabilities;
        const labels = Object.keys(probabilities);
        const data = Object.values(probabilities).map(p => p * 100);
        
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: '概率分布 (%)',
                    data: data,
                    backgroundColor: [
                        'rgba(52, 152, 219, 0.7)',
                        'rgba(46, 204, 113, 0.7)',
                        'rgba(231, 76, 60, 0.7)',
                        'rgba(241, 196, 15, 0.7)'
                    ],
                    borderColor: [
                        'rgba(52, 152, 219, 1)',
                        'rgba(46, 204, 113, 1)',
                        'rgba(231, 76, 60, 1)',
                        'rgba(241, 196, 15, 1)'
                    ],
                    borderWidth: 1,
                    borderRadius: 5,
                    maxBarThickness: 50
                }]
            },
            options: {
                responsive: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        ticks: {
                            callback: value => value + '%'
                        }
                    }
                },
                animation: false
            }
        });
        
        // 使用html2canvas截图
        setTimeout(() => {
            html2canvas(resultContainer, {
                scale: 1,
                useCORS: true,
                logging: false
            }).then(canvas => {
                // 将canvas转为blob
                canvas.toBlob(blob => {
                    // 创建FormData
                    const formData = new FormData();
                    formData.append('image', blob, fileName);
                    formData.append('patient_id', patientInfo.id || '未知ID');
                    formData.append('patient_name', patientInfo.name || '未知姓名');
                    formData.append('date', dateStr);
                    
                    // 发送到服务器保存
                    fetch('/save_result', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showAlert('保存成功', '诊断结果已保存', 'success');
                        } else {
                            showAlert('保存失败', data.message, 'danger');
                        }
                    })
                    .catch(error => {
                        console.error('保存结果失败:', error);
                        showAlert('保存失败', '无法保存诊断结果', 'danger');
                    })
                    .finally(() => {
                        // 移除临时元素
                        document.body.removeChild(resultContainer);
                    });
                }, 'image/png');
            });
        }, 500);
    }
    
    // 生成疾病信息HTML
    function generateDiseaseInfoHTML(diseaseName) {
        if (!diseaseConfig || !diseaseConfig[diseaseName]) {
            return '<p>暂无相关疾病信息</p>';
        }
        
        const disease = diseaseConfig[diseaseName];
        
        let html = `
            <div style="background-color: #f8f9fa; padding: 15px; border-radius: 8px;">
                <h5 style="color: #3498db; margin-bottom: 10px;">${disease.name}</h5>
                <p style="margin-bottom: 15px;">${disease.description}</p>
        `;
        
        if (disease.risk_factors && disease.risk_factors.length > 0) {
            html += '<h6 style="margin-top: 15px; margin-bottom: 10px;">风险因素</h6><ul style="padding-left: 20px;">';
            disease.risk_factors.forEach(factor => {
                html += `<li style="margin-bottom: 5px;">${factor}</li>`;
            });
            html += '</ul>';
        }
        
        if (disease.suggestions && disease.suggestions.length > 0) {
            html += '<h6 style="margin-top: 15px; margin-bottom: 10px;">建议</h6><ul style="padding-left: 20px;">';
            disease.suggestions.forEach(suggestion => {
                html += `<li style="margin-bottom: 5px;">${suggestion}</li>`;
            });
            html += '</ul>';
        }
        
        html += '</div>';
        return html;
    }
    
    // 添加缺失的函数
    function updatePatientInfo(patientInfo) {
        // 更新患者信息区域
        const patientInfoElement = document.getElementById('patient-info');
        if (patientInfoElement) {
            patientInfoElement.innerHTML = `
                <dl class="row mb-0">
                    <dt class="col-sm-3">病历号:</dt>
                    <dd class="col-sm-9">${patientInfo.id || '未填写'}</dd>
                    
                    <dt class="col-sm-3">姓名:</dt>
                    <dd class="col-sm-9">${patientInfo.name || '未填写'}</dd>
                    
                    <dt class="col-sm-3">性别:</dt>
                    <dd class="col-sm-9">${patientInfo.gender || '未填写'}</dd>
                    
                    <dt class="col-sm-3">年龄:</dt>
                    <dd class="col-sm-9">${patientInfo.age ? patientInfo.age + '岁' : '未填写'}</dd>
                    
                    <dt class="col-sm-3">检查日期:</dt>
                    <dd class="col-sm-9">${patientInfo.exam_date || new Date().toISOString().split('T')[0]}</dd>
                </dl>
            `;
        }
    }

    // 添加调试日志，帮助查看返回的结果结构
    function updateResultsUI(results) {
        console.log('Received analysis results:', JSON.stringify(results));
        
        // 确保诊断信息存在
        if (!results.diagnosis) {
            showError('分析结果中缺少诊断信息');
            return;
        }
        
        // 其他更新UI的代码
        // ...
    }

    // 显示错误信息
    function showError(message) {
        showAlert('错误', message, 'danger');
        resetProgress();
    }

    // 更新处理状态的函数
    function updateProcessingStatus(data) {
        let statusContainer = document.getElementById('processing-status');
        if (!statusContainer) {
            statusContainer = document.createElement('div');
            statusContainer.id = 'processing-status';
            statusContainer.className = 'processing-status-container';
            document.querySelector('.progress').after(statusContainer);
        }

        // 如果是处理完成的状态
        if (data.status === 'complete') {
            const statusHtml = `
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <div class="mb-2">
                        <strong>批量处理完成！</strong>
                    </div>
                    <div class="small">
                        <p class="mb-1">成功处理: ${data.success_count} 个文件</p>
                        <p class="mb-1">处理失败: ${data.failed_count} 个文件</p>
                        <p class="mb-0">结果保存路径: <code>${data.output_dir}</code></p>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            `;
            statusContainer.innerHTML = statusHtml;
        } else {
            // 处理中的状态
            const statusHtml = `
                <div class="alert alert-info alert-dismissible fade show" role="alert">
                    <div class="mb-2">
                        <strong>正在处理第 ${data.file_index} 个文件</strong>
                    </div>
                    <div class="small">
                        <p class="mb-0">当前诊断: ${data.diagnosis}</p>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            `;
            statusContainer.innerHTML = statusHtml;
        }
    }

    // 添加批量处理单选框的事件监听
    const batchModeSingle = document.getElementById('batch-mode-single');
    const batchModeBoth = document.getElementById('batch-mode-both');
    const resultSections = document.querySelectorAll('.result-section');
    
    // 添加模式切换事件监听
    const singleModeTab = document.querySelector('button[data-bs-target="#single-eye"]');
    const bothModeTab = document.querySelector('button[data-bs-target="#both-eyes"]');
    
    // 模式切换时同步批量处理状态和显示/隐藏状态
    singleModeTab.addEventListener('shown.bs.tab', function() {
        // 当切换到单眼模式时，根据当前模式的批量处理开关状态显示/隐藏结果区域
        toggleResultSections(batchModeSingle.checked);
    });
    
    bothModeTab.addEventListener('shown.bs.tab', function() {
        // 当切换到双眼模式时，根据当前模式的批量处理开关状态显示/隐藏结果区域
        toggleResultSections(batchModeBoth.checked);
    });

    function toggleResultSections(checked) {
        resultSections.forEach(section => {
            if (checked) {
                section.classList.add('d-none');
                // 只在需要显示2行时修改grid布局
                document.querySelector('.grid-container').style.gridTemplateRows = 'auto auto';
            } else {
                section.classList.remove('d-none');
                // 恢复时移除内联样式，使用CSS默认值
                document.querySelector('.grid-container').style.gridTemplateRows = '';
            }
        });
    }
    
    batchModeSingle.addEventListener('change', function(e) {
        toggleResultSections(e.target.checked);
    });
    
    batchModeBoth.addEventListener('change', function(e) {
        toggleResultSections(e.target.checked);
    });

    // 在文件选择发生变化时触发患者信息匹配
    document.getElementById('single-folder-input').addEventListener('change', function() {
        if (window.patientInfoModule && document.getElementById('batch-patient-info').checked) {
            window.patientInfoModule.matchPatientsWithImages();
        }
    });

    document.getElementById('left-folder-input').addEventListener('change', function() {
        if (window.patientInfoModule && document.getElementById('batch-patient-info').checked) {
            window.patientInfoModule.matchPatientsWithImages();
        }
    });
}); 